<?php

class SiteController extends Controller
{

  /**
   * Declares class-based actions.
   */
  public function actions()
  {
    return array(
      // captcha action renders the CAPTCHA image displayed on the contact page
      'captcha'=>array(
        'class'=>'CCaptchaAction',
        'backColor'=>0xFFFFFF,
      ),
      // page action renders "static" pages stored under 'protected/views/site/pages'
      // They can be accessed via: index.php?r=site/page&view=FileName
      'page'=>array(
        'class'=>'CViewAction',
      ),
    );
  }

  /**
   * This is the default 'index' action that is invoked
   * when an action is not explicitly requested by users.
   */
  public function actionIndex()
  {
    $trans = array("ą" => "a", "ć" => "c", "ę" => "e", "ł" => "l", "ń" => "n", "ó" => "o", "ś" => "s", "ź" => "z", "ż" => "z", "Ą" => "a", "Ć" => "c", "Ę" => "e", "Ł" => "l", "Ń" => "n", "Ó" => "o", "Ś" => "s", "Ź" => "z", "Ż" => "z",);
    $requested_file = ltrim(strtr(parse_url(urldecode(Yii::app()->request->requestUri), PHP_URL_PATH), $trans), '/');
    if (!file_exists(Yii::app()->params['staticFilesDir'] . DIRECTORY_SEPARATOR . $requested_file) or empty($requested_file)) {
      $requested_file = 'index.html';
    }

    Yii::import('application.extensions.phpQuery.phpQuery');

    // get requested resource ex. "oasis_tours.html"
    $doc = phpQuery::newDocumentFileHTML(Yii::app()->params['staticFilesDir'] . DIRECTORY_SEPARATOR . $requested_file);

    // add styles
    $baseUrl = Yii::app()->baseUrl;
    $links = pq("head link[type='text/css']");
    foreach($links as $link) {
      $css_href = pq($link)->attr('href');
      $css_media = pq($link)->attr('media');
      $css_rel = pq($link)->attr('rel');
      if ($css_rel !== 'alternate stylesheet') {
        Yii::app()->clientScript->registerCssFile($baseUrl . Yii::app()->params['staticFilesDir'] . '/'. $css_href, $css_media);
      }
    }


    $imContent = pq('#imContent');
    //var_dump(PremiumArea::is_full_premium_page($requested_file));
    //echo $requested_file;
    //echo '[tmp] : Touroperator: ' . PremiumArea::get_touroperator_id_by_requested_file($requested_file);

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [ premium area ] */

    $check_access = PremiumArea::check_access_to_page($requested_file);

    if (!empty($check_access)) {//sprawdzamy czy wogóle sprawa dotyczy strony płatnej
      $imPage = $imContent->find('#imPage');
      $imContentChilds = $imPage->children('div');
      $i = 0;

      foreach($imContentChilds as $child) {
        if ($check_access === true || $i === 0) {//sprawdzamy czy ma pełen dostęp
          pq($child)->addClass('area_' . $i);
        } else {//jeśli nie to blokujemy treść
          pq($child)->addClass('protected_area area_' . $i);
          if($i === 1) {
            $html = $check_access;
          }

          pq($child)->html($html);
          $html = '';
        }
        
        $i++;
        
      }
    }
    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [ end premium area ] */


    // replace imgs src
    $imgs = $imContent->find('img');
    foreach($imgs as $img) {
      $img_src = Yii::app()->params['staticFilesDir'] . DIRECTORY_SEPARATOR . pq($img)->attr('src');
      $fp = fopen($img_src, "rb", 0);
      $img_embeded_data = fread($fp, filesize($img_src));
      fclose($fp);
      $img_embeded_data = chunk_split(base64_encode($img_embeded_data));
      pq($img)->attr('src', 'data:img/jpg;base64,' . $img_embeded_data);
    }

    $this->render('index', array('imContent' => $imContent));
  }

  public function actionMapa()
  {
    $geo_users = Yii::app()->db->createCommand()
    ->select('premium_option_valid_thru,latlng, point_desc, marker_icon_url, agent_on_map')
    ->from('tbl_profiles')
    ->where('agent_on_map=:agent_on_map AND tbl_users.premium_option_valid_thru >= ' . time(), array(':agent_on_map'=>1))
	->join('tbl_users','tbl_users.id=tbl_profiles.user_id')
    ->queryAll();
    $this->render('mapa', array('geo_users' => $geo_users));
  }

  /**
   * This is the action to handle external exceptions.
   */
  public function actionError()
  {
      if($error=Yii::app()->errorHandler->error)
      {
        if(Yii::app()->request->isAjaxRequest)
          echo $error['message'];
        else
            $this->render('error', $error);
      }
  }

  public function actionFinalize_Payment_Success()
  {
    $msg = 'Udało się sfinalizować transakcję!';

    if(!PremiumArea::finalize_payment_success_form()) {
      //Yii::app()->controller->redirect(array('/site/message', 'msg'=>'Błąd finalizacji transakcji!'));
      $msg = 'Błąd finalizacji transakcji!';
    }

    $this->render_msg($msg);
  }

  public function actionFinalize_Payment_Error()
  {
    $msg = 'Nie udało się sfinalizować transakcji!';

    if(!PremiumArea::finalize_payment_error_form()) {
      $msg = 'Wystąpił nieoczekiwany błąd';
    }

    $this->render_msg($msg);
  }

  public function actionMessage()
  {
    $this->render_msg();
  }

  public function render_msg($msg = null)
  {
    if(!$msg) {
      $msg = 'Operacja nie powiodła się! Spróbuj ponownie lub skontaktuj się z administratorem systemu.';
    }

    if(isset($_GET['msg'])) {
      $msg = $_GET['msg'];
    }

    $this->render('message', array('msg' => $msg));
  }

  public function actionCheck_Sms_Code()
  {
    $backlink = (isset($_GET['backlink']) ? $_GET['backlink'] : '');

    if(PremiumArea::validate_sms_form()) {
      //TODO - wyświetlić rzeczywistą wiadomość
      $this->render_msg(PremiumArea::prepare_link('Przejdź do płatej podstrony, do której wykupiłeś dostęp sms-owy', $backlink));
      return;
    } else {
      if(isset($_GET['operator_id'])) {
        PremiumArea::_dump($backlink);
        if(!PremiumArea::get_sms_code_cookie($_GET['operator_id'])) {

          $form = PremiumArea::get_sms_form($_GET['operator_id'], $backlink);
          $this->render('check_sms_code',array('form'=>$form));
          return;
        } else {
          PremiumArea::_echo('JEST COOKIE!');
          if($backlink != ''){
            PremiumArea::_echo('hello');
            $this->render_msg(PremiumArea::prepare_link('Przejdź do płatej podstrony, do której wykupiłeś dostęp sms-owy', $backlink));
          } else {
            $this->actionIndex();
          }
        }
      } else {
        $this->render_msg();
      }

    }

  }
}